// packageD/pages/translate/translate.js
import { language } from '../utils/language';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        gobackIcon: '',
        showPopup: false, // 展示 Popup 弹窗
        languageArr: language, // 所有语种
        currentLanguage: {
            title: '英文',
            code: 'en',
        }, // 当前默认展示的语种
        iptVal: '',
        translatrRes: Object,
    },

    // 弹出Popup弹窗
    onShowPopup() {
        this.setData({ showPopup: true });
    },

    // 取消Popup弹窗
    onClosePopup() {
        this.setData({ showPopup: false });
    },

    // 监听搜索框值得改变
    onIPtChange(e) {
        this.setData({
            iptVal: e.detail,
        });
    },

    // 点击搜索按钮
    onIPtSearch() {
        const { iptVal, currentLanguage } = this.data;
        if (iptVal) {
            this.setData({ translatrRes: false });
            this.baiduBCE(currentLanguage.code, iptVal);
        } else {
            Toast('请输入内容');
        }
    },

    // 返回上一页
    goback() {
        wx.navigateBack({
            delta: 1,
        })
    },

    // 点击列表，选择语种
    onHandleCode(e) {
        const { title, code } = e.currentTarget.dataset;
        this.setData({
            currentLanguage: {
                title,
                code
            },
        }, () => {
            this.setData({ showPopup: false });
        })
    },

    // 封装函数，根据语种代号code，来找到名称title
    getTitleForCode(code) {
        let title;
        language.forEach(item => {
            item.name.forEach(item2 => {
                if (item2.code === code) {
                    title = item2.title;
                };
            });
        });
        return title;
    },

    /** 
     * 翻译
    */
    baiduBCE(code, iptVal) {
        const that = this;
        wx.cloud.callFunction({
            name: 'getOCRToken',
            data: {
                APIKEY: "wocPDtGWxhG2GcV1C8RPII5t",
                SECKEY: "vSXSo317T1KdzA8wUHjFVuTYnwFGjpk3",
            }
        }).then(res1 => {
            wx.showLoading({
                title: '词语或句子翻译中...',
            })
            const access_token = res1.result;
            wx.request({
                url: `https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=${access_token}`,
                data: {
                    from: 'auto', // 自动检测
                    to: code, // 需要翻译的语种
                    q: iptVal, // 需要翻译的词
                },
                method: 'POST',
                dataType: 'json',
                header: {
                    'content-type': 'application/json;charset=utf-8' // 必须的        
                },
                success: (res) => {
                    wx.hideLoading();
                    console.log(res.data.result);
                    const { result } = res.data;
                    that.setData({
                        translatrRes: {
                            from: that.getTitleForCode(result.from),
                            to: that.getTitleForCode(result.to),
                            src: result.trans_result[0].src,
                            dst: result.trans_result[0].dst,
                        }
                    });
                },
                fail: (res) => {
                    wx.hideLoading();
                    Toast.fail('出错啦，请稍后再试')
                    console.log('fail：', res.data);
                }
            })
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // this.baiduBCE()
        // console.log(language);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const gobackTop = wx.getMenuButtonBoundingClientRect();
        this.setData({
            gobackIcon: gobackTop.top + 8,
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})